using AutoMapper;
using Interface;
using Microsoft.Extensions.Logging;
using Model.Dto.Student;
using Model.Entity;
using Model.Vo;
using Repository;
using SqlSugar;

namespace Service;

/// <summary>
/// 学生服务实现类
/// </summary>
/// <remarks>
/// 继承BaseService，提供学生特定的查询功能
/// </remarks>
public class StudentService : BaseService<Student, StudentVo>, IStudentService
{
    private readonly ISqlSugarClient _db;
    private readonly IMapper _mapper;

    /// <summary>
    /// 构造函数
    /// </summary>
    public StudentService(
        ISqlSugarClient db, 
        BaseRepository<Student> repository, 
        IMapper mapper, 
        ILogger<BaseService<Student, StudentVo>> logger) 
        : base(db, repository, mapper, logger)
    {
        _db = db;
        _mapper = mapper;
    }

    /// <summary>
    /// 分页查询学生（支持多条件过滤）
    /// </summary>
    /// <param name="query">查询参数</param>
    /// <returns>学生VO列表</returns>
    /// <remarks>
    /// 使用SqlSugar的WhereIF简化条件判断，使用Select直接投影到VO，避免查询不需要的字段（如密码）
    /// </remarks>
    public async Task<List<StudentVo>> GetPageAsync(StudentQuery query)
    {
        // 使用WhereIF链式调用简化条件判断，使用Select直接投影到VO
        return await _db.Queryable<Student>()
            .WhereIF(!string.IsNullOrWhiteSpace(query.No), s => s.No.Contains(query.No))
            .WhereIF(!string.IsNullOrWhiteSpace(query.Name), s => s.Name.Contains(query.Name))
            .WhereIF(!string.IsNullOrWhiteSpace(query.Grade), s => s.Grade == query.Grade)
            .WhereIF(!string.IsNullOrWhiteSpace(query.Major), s => s.Major.Contains(query.Major))
            .WhereIF(!string.IsNullOrWhiteSpace(query.Class), s => s.Class == query.Class)
            .WhereIF(!string.IsNullOrWhiteSpace(query.Sex), s => s.Sex == query.Sex)
            .OrderBy(s => s.Id)
            .Skip((query.Page - 1) * query.PageSize)
            .Take(query.PageSize)
            .Select(s => new StudentVo
            {
                Id = s.Id,
                No = s.No,
                Name = s.Name,
                Mobile = s.Mobile,
                Grade = s.Grade,
                Major = s.Major,
                Class = s.Class,
                Sex = s.Sex,
                CreateTime = s.CreateTime,
                UpdateTime = s.UpdateTime
            })
            .ToListAsync();
    }
}
